const dataCount = 10;
const networkList = {
    timeData:[],
};
const  discList = {
    timeData : [],
    readRate : [],
    writeRate : [],
}
const color = [
    [ '#00d887','rgba(0, 216, 135, 0.4)','rgba(0, 216, 135, 0.1)'],
    [ '#0184d5','rgba(1, 132, 213, 0.4)','rgba(1, 132, 213, 0.1)'],
    [ '#3B2667','rgba(188,120,236,0.4)','rgba(188,120,236, 0.1)'],
    [ '#F8D800','rgba(248,216,0, 0.4)','rgba(248,216,0, 0.1)'],
    [ '#EA5455','rgba(234,84,85, 0.4)','rgba(234,84,85, 0.1)'],
    [ '#32CCBC','rgba(50,204,188, 0.4)','rgba(50,204,188, 0.1)'],
    [ '#DE4313','rgba(222,67,19, 0.4)','rgba(222,67,19, 0.1)'],
    [ '#3CD500','rgba(60,213,0, 0.4)','rgba(60,213,0, 0.1)'],
    [ '#C346C2','rgba(195,70,194, 0.4)','rgba(195,70,194, 0.1)'],
    [ '#360940','rgba(54,9,64, 0.4)','rgba(54,9,64, 0.1)'],
]
templateViewInit = function () {
    cpu()
    memory()
    jvm()
    disc()
    network()

    top.tools.ajax({
        url: '/system/info',
        type: 'POST',
        dataType: 'json',
        loading:false,
        successFun: function (res) {
            if (res.code == 200) {
                console.log(res.data)
                osInfo(res.data.osInfo);
                updateCpu(res.data.oSRuntimeInfo);
                updateMemory(res.data.oSRuntimeInfo);
                // updateJvm(res.data.jvm);

                updateTable(res.data.oSRuntimeInfo.disksList,res.data.oSRuntimeInfo.networkList);

                updateDisc(res.data.oSRuntimeInfo);
                updateNetwork(res.data.oSRuntimeInfo)

            }
        }
    });

    startPolling();
}

function startPolling(interval = 5000) {
    function poll() {
        top.tools.ajax({
            url: '/system/info',
            type: 'POST',
            dataType: 'json',
            loading:false,
            successFun: function (res) {
                if (res.code == 200) {
                    osInfo(res.data.osInfo);
                    updateCpu(res.data.oSRuntimeInfo);
                    updateMemory(res.data.oSRuntimeInfo);
                    // updateJvm(res.data.jvm);

                    updateDisc(res.data.oSRuntimeInfo);
                    updateNetwork(res.data.oSRuntimeInfo)
                }
                setTimeout(poll, interval);
            }
        });

    }

    // 开始第一次轮询
    poll();
}

function getSysInfo() {

}

function osInfo(osInfo) {
    let html = '';
    let os = osInfo.os.toLowerCase();
    if (os.includes('windows')) {
        html += ' <span class="iconfont icon-win"></span>'
    } else if (os.includes('centos')) {
        html += ' <span class="iconfont icon-centso"></span>'
    } else {
        html += ' <span class="iconfont icon-linux"></span>'
    }
    html += ' <span>系统：' + osInfo.os + '</span>'
    html += ' <span>系统架构：' + osInfo.osArch + '</span>'
    html += ' <span>运行时长：' + osInfo.bootTime.split('分')[0] + '分</span>'
    html += ' <span>主机IP：' + osInfo.host + '</span>'
    html += ' <span>主机名称：' + osInfo.hostName + '</span>'

    $('#sysinfo').html(html)
}

function cpu() {
    // 基于准备好的dom，初始化echarts实例
    // cpuChart = echarts.getInstanceByDom(document.querySelector("#cpu")).showLoading();
    let cpuChart = echarts.init(document.querySelector("#cpu")); //.showLoading()
    let option = {
        title: {
            text: 'CPU 占有率 \n ',
            x: 'center',
            y: 'center',
            textStyle: {
                fontWeight: 'normal',
                color: '#1a1919',
                fontSize: '30'
            }
        },
        color: ['#e3e3e3'],


        series: [{
            name: 'CPU 详情',
            type: 'pie',
            clockWise: true,
            radius: ['100%', '85%'],
            itemStyle: {
                normal: {
                    label: {
                        show: false
                    },
                    labelLine: {
                        show: false
                    }
                }
            },
            hoverAnimation: false,
            data: [{
                value: 0,
                name: '使用率',
                itemStyle: {
                    normal: {
                        color: { // 完成的圆环的颜色
                            colorStops: [{
                                offset: 0,
                                color: '#00cefc' // 0% 处的颜色
                            }, {
                                offset: 1,
                                color: '#367bec' // 100% 处的颜色
                            }]
                        },
                        label: {
                            show: false
                        },
                        labelLine: {
                            show: false
                        }
                    }
                }
            }, {
                name: "空闲率",
                value: (100 - 0)
            }]
        }]
    };
    // 使用刚指定的配置项和数据显示图表。
    cpuChart.setOption(option);
    cpuChart.showLoading();
}

function memory() {
    let memoryChart = echarts.init(document.querySelector("#memory")); //.showLoading()
    let data = [];
    let option = {
        color: [
            "#28C76F",
            "#F8D800",
            "#e3e3e3",
            "#EA5455"
        ],
        series: [{
            name: '内存详情',
            type: 'pie',
            clockWise: true,
            radius: ['100%', '85%'],
            itemStyle: {
                normal: {
                    label: {
                        show: false
                    },
                    labelLine: {
                        show: false
                    }
                }
            },
            hoverAnimation: false,
            data: data
        }]
    };
    // 使用刚指定的配置项和数据显示图表。
    memoryChart.setOption(option);
    memoryChart.showLoading();
}

function jvm(){
    let jvmChart = echarts.init(document.querySelector("#jvm")); //.showLoading()
    let data = [];
    let option = {
        color: [
            "#28C76F",
            "#F8D800",
            "#e3e3e3",
            "#EA5455"
        ],
        series: [{
            name: 'JVM详情',
            type: 'pie',
            clockWise: true,
            radius: ['100%', '85%'],
            itemStyle: {
                normal: {
                    label: {
                        show: false
                    },
                    labelLine: {
                        show: false
                    }
                }
            },
            hoverAnimation: false,
            data: data
        }]
    };
    // 使用刚指定的配置项和数据显示图表。
    jvmChart.setOption(option);
    jvmChart.showLoading();
}

function disc() {
    var diskChart = echarts.init(document.getElementById('disk'));
    let option = {
        tooltip: {
            trigger: 'axis',
            axisPointer: {
                lineStyle: {
                    color: '#dddc6b'
                }
            }
        },
        legend: {
            top: '0%',
            data: ['读取', '写入'],
            textStyle: {
                fontSize: '12',
            }
        },
        grid: {
            left: '10',
            top: '30',
            right: '10',
            bottom: '10',
            containLabel: true
        },

        xAxis: [{
            type: 'category',
            boundaryGap: false,
            axisLabel: {
                textStyle: {
                    fontSize: 12,
                },
            },
            axisLine: {
                lineStyle: {
                }

            },
            data: discList.timeData
        }, {
            axisPointer: {show: false},
            axisLine: {show: false},
            position: 'bottom',
            offset: 20,
        }],
        yAxis: [{
            type: 'value',
            axisTick: {show: false},
            axisLabel: {
                formatter: '{value} Kb/s',
                textStyle: {
                    fontSize: 12,
                },
            }
        }],
        series: [
            {
                name: '读取',
                type: 'line',
                smooth: true,
                symbol: 'circle',
                symbolSize: 5,
                showSymbol: false,
                lineStyle: {

                    normal: {
                        color: '#0184d5',
                        width: 2
                    }
                },
                areaStyle: {
                    normal: {
                        color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [{
                            offset: 0,
                            color: 'rgba(1, 132, 213, 0.4)'
                        }, {
                            offset: 0.8,
                            color: 'rgba(1, 132, 213, 0.1)'
                        }], false),
                        shadowColor: 'rgba(0, 0, 0, 0.1)',
                    }
                },
                itemStyle: {
                    normal: {
                        color: '#0184d5',
                        borderColor: 'rgba(221, 220, 107, .1)',
                        borderWidth: 12
                    }
                },
                data: discList.readRate

            },
            {
                name: '写入',
                type: 'line',
                smooth: true,
                symbol: 'circle',
                symbolSize: 5,
                showSymbol: false,
                lineStyle: {

                    normal: {
                        color: '#00d887',
                        width: 2
                    }
                },
                areaStyle: {
                    normal: {
                        color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [{
                            offset: 0,
                            color: 'rgba(0, 216, 135, 0.4)'
                        }, {
                            offset: 0.8,
                            color: 'rgba(0, 216, 135, 0.1)'
                        }], false),
                        shadowColor: 'rgba(0, 0, 0, 0.1)',
                    }
                },
                itemStyle: {
                    normal: {
                        color: '#00d887',
                        borderColor: 'rgba(221, 220, 107, .1)',
                        borderWidth: 12
                    }
                },
                data: discList.writeRate
            },
        ]

    };
    // 使用刚指定的配置项和数据显示图表。
    diskChart.setOption(option);
    diskChart.showLoading();
}

function network(){
    var networkChart = echarts.init(document.getElementById('network'));
    let option = {
        tooltip: {
            trigger: 'axis',
            axisPointer: {
                lineStyle: {
                    color: '#dddc6b'
                }
            }
        },
        legend: {
            top: '0%',
            data: [],
            textStyle: {
                fontSize: '12',
            }
        },
        grid: {
            left: '10',
            top: '30',
            right: '10',
            bottom: '10',
            containLabel: true
        },

        xAxis: [{
            type: 'category',
            boundaryGap: false,
            axisLabel: {
                textStyle: {
                    fontSize: 12,
                },
            },
            axisLine: {
                lineStyle: {
                }

            },
            data: []
        }, {
            axisPointer: {show: false},
            axisLine: {show: false},
            position: 'bottom',
            offset: 20,
        }],
        yAxis: [{
            type: 'value',
            axisTick: {show: false},
            axisLabel: {
                formatter: '{value} Kbps',
                textStyle: {
                    fontSize: 12,
                },
            }
        }],
        series: []
    };
    // 使用刚指定的配置项和数据显示图表。
    networkChart.setOption(option);
    networkChart.showLoading();
}

function updateTable(disksList,networkList){
    // 已知数据渲染
    layui.table.render({
        elem: '#discTable',
        height: 320,
        cols: [[ //标题栏
            {field: 'dirName', title: '挂载',align:'center', width: 80},
            {field: 'typeName', title: '类型',align:'center', width: 80},
            {field: 'totalStr', title: '容量',align:'center', width: 120, templet: '<span style="display: flex;">{{= d.totalStr }}</span>'},
            {field: 'freeStr', title: '可用',align:'center', width: 120, templet: '<span style="display: flex;">{{= d.freeStr }}</span>'},
            {field: 'usedStr', title: '已用',align:'center', width: 120, templet: '<span style="display: flex;">{{= d.usedStr }}</span>'},
            {field: 'usageStr', title: '使用率',align:'center', templet:function(d){
                    return '<div class="layui-progress layui-progress-big" lay-filter="usage-progress" lay-showpercent="true"><div class="layui-progress-bar" lay-percent="'+(d.usageStr?d.usageStr:'0%') +'"></div></div>'
                }}
        ]],
        data: disksList,
        skin: 'line', // 表格风格
    });
    layui.table.render({
        elem: '#networkTable',
        height: 320,
        cols: [[ //标题栏
            {field: 'networkName', title: '名称',align:'center', width: 80},
            {field: 'ipv4Address', title: 'IPv4',align:'center'},
            {field: 'ipv6Address', title: 'IPv6',align:'center'}
        ]],
        data: networkList,
        skin: 'line', // 表格风格
    });
    // 渲染进度条组件
    layui.element.render('progress', 'usage-progress');
}

function updateCpu(oSRuntimeInfo) {
    let cpuUsage = parseFloat(oSRuntimeInfo.cpuUsageStr);
    let echartsInstance = echarts.getInstanceByDom(document.querySelector("#cpu"));
    echartsInstance.setOption({
        tooltip: {
            trigger: "item",
            formatter: "{a} <br/>" //{b}:  {d}%
                +"使用率: "+oSRuntimeInfo.cpuUsageStr+"<br/>"
                +"空闲率: "+(100 - cpuUsage)+"%"
            ,
            position: function (p) {
                //其中p为当前鼠标的位置
                return [p[0] + 10, p[1] - 10];
            }
        },
        title: {
            text: 'CPU 占有率 \n '+oSRuntimeInfo.cpuUsageStr,
        },
        series: [{
            data: [
                {value: cpuUsage, name: "使用率",itemStyle: {
                        normal: {
                            color: { // 完成的圆环的颜色
                                colorStops: [{
                                    offset: 0,
                                    color: '#00cefc' // 0% 处的颜色
                                }, {
                                    offset: 1,
                                    color: '#367bec' // 100% 处的颜色
                                }]
                            },
                            label: {
                                show: false
                            },
                            labelLine: {
                                show: false
                            }
                        }
                    }},
                {value: (100 - cpuUsage), name: "空闲率"}
            ]
        }]
    });
    echartsInstance.hideLoading(); // 去除loading
}

function updateMemory(oSRuntimeInfo) {
    let memoryUsage = parseFloat(oSRuntimeInfo.usedStr).toFixed(2);
    let totalMemoryUsage = parseFloat(oSRuntimeInfo.totalStr).toFixed(2);
    let swapTotalMemory = parseFloat(oSRuntimeInfo.swapTotalStr).toFixed(2);
    let swapMemoryUsage = parseFloat(oSRuntimeInfo.swapUsedStr).toFixed(2);
    let freeMemory = parseFloat(totalMemoryUsage - memoryUsage).toFixed(2)
    let freeSwapMemory = parseFloat(swapTotalMemory - swapMemoryUsage).toFixed(2)
    let data = [{
        value: memoryUsage, name: '已用内存', itemStyle: {
            normal: {
                color: { // 完成的圆环的颜色
                    colorStops: [{
                        offset: 0,
                        color: '#00cefc' // 0% 处的颜色
                    }, {
                        offset: 1,
                        color: '#367bec' // 100% 处的颜色
                    }]
                },
                label: {
                    show: false
                },
                labelLine: {
                    show: false
                }
            }
        }
    }, {name: "可用内存", value: freeMemory}];
    if (oSRuntimeInfo.swapTotalMemory && oSRuntimeInfo.swapTotalMemory > 0){
        data.push({
            value: swapMemoryUsage,
            name: '已用虚拟内存'
        })
        data.push({
            name: "可用虚拟内存",
            value: freeSwapMemory
        })
    }

    let echartsInstance = echarts.getInstanceByDom(document.querySelector("#memory"));
    echartsInstance.setOption({
        tooltip: {
            trigger: "item",
            formatter: "{a} <br/>内存总量: " + oSRuntimeInfo.totalStr + "<br/> "
                + "已用内存: "+ oSRuntimeInfo.usedStr+"<br/> "
                + "可用内存: "+ freeMemory + oSRuntimeInfo.usedStr.split(" ")[1]+"<br/> "
                + (oSRuntimeInfo.swapTotalMemory && oSRuntimeInfo.swapTotalMemory > 0 ?
                    "虚拟内存总量: " + oSRuntimeInfo.swapTotalStr + "<br/>"+
                    "已用虚拟内存: " + oSRuntimeInfo.swapUsedStr + "<br/>"+
                    "可用虚拟内存: " +freeSwapMemory+ oSRuntimeInfo.swapUsedStr.split(" ")[1] + "<br/>"
                    : ""),
            position: function (p) {
                //其中p为当前鼠标的位置
                return [p[0] + 10, p[1] - 10];
            }
        },
        title: {
            text: '内存使用率 \n ' + oSRuntimeInfo.usageStr,
            x: 'center',
            y: 'center',
            textStyle: {
                fontWeight: 'normal',
                color: '#1a1919',
                fontSize: '30'
            }
        },
        series: [{
            data: data
        }]
    });
    echartsInstance.hideLoading(); // 去除loading
}
function updateJvm(jvm){
    let jvmUsage = parseFloat(jvm.user).toFixed(2);
    let freeUsage = parseFloat(jvm.free).toFixed(2);
    let data = [{
        value: jvmUsage, name: '已用内存', itemStyle: {
            normal: {
                color: { // 完成的圆环的颜色
                    colorStops: [{
                        offset: 0,
                        color: '#00cefc' // 0% 处的颜色
                    }, {
                        offset: 1,
                        color: '#367bec' // 100% 处的颜色
                    }]
                },
                label: {
                    show: false
                },
                labelLine: {
                    show: false
                }
            }
        }
    }, {name: "可用内存", value: freeUsage}];


    let echartsInstance = echarts.getInstanceByDom(document.querySelector("#jvm"));
    echartsInstance.setOption({
        tooltip: {
            trigger: "item",
            formatter: "{a} <br/>JVM内存总量: " + jvm.total + "<br/> "
                + "JVM最大可申请: " + jvm.max + "<br/>"
                + "已用内存："+jvm.user+"<br/>"
                + "空闲内存："+jvm.free+"<br/>",
            position: function (p) {
                //其中p为当前鼠标的位置
                return [p[0] + 10, p[1] - 10];
            }
        },
        title: {
            text: 'JVM使用率 \n ' + jvm.usageRate,
            x: 'center',
            y: 'center',
            textStyle: {
                fontWeight: 'normal',
                color: '#1a1919',
                fontSize: '30'
            }
        },
        series: [{
            data: data
        }]
    });
    echartsInstance.hideLoading(); // 去除loading
}
function updateDisc(oSRuntimeInfo){
    const now = new Date();
    const time = now.toLocaleTimeString();

    if (discList.timeData.length > dataCount) {
        discList.readRate.shift();
        discList.writeRate.shift();
        discList.timeData.shift();
    }

    discList.readRate.push(oSRuntimeInfo.diskReadRate);
    discList.writeRate.push(oSRuntimeInfo.diskWriteRate);
    discList.timeData.push(time);
    let echartsInstance = echarts.getInstanceByDom(document.querySelector("#disk"));
    echartsInstance.setOption({
        xAxis: {
            data: discList.timeData
        },
        series: [
            {
                name: '读取',
                data: discList.readRate
            },
            {
                name: '写入',
                data: discList.writeRate
            }
        ]
    });
    echartsInstance.hideLoading(); // 去除loading
}
function updateNetwork(oSRuntimeInfo){
    const now = new Date();
    const time = now.toLocaleTimeString();
    let list = oSRuntimeInfo.networkList;
    let series = [];
    let data = [];
    let  i = 0;
    for (let j = 0; j < list.length; j++) {
        if (networkList[list[j].networkName]) {
            if (networkList.timeData.length > dataCount) {
                networkList[list[j].networkName].accept.shift();
                networkList[list[j].networkName].send.shift();
                networkList.timeData.shift();
            }
        }else {
            networkList[list[j].networkName] = {
                accept:[],
                send:[],
            }
        }
        let accept = parseFloat(list[j].accept / 1024.0).toFixed(2);
        let send = parseFloat(list[j].send / 1024.0).toFixed(2);
        networkList[list[j].networkName].accept.push(accept);
        networkList[list[j].networkName].send.push(send);

        series.push({
            name: list[j].networkName+'↑',
            type: 'line',
            smooth: true,
            symbol: 'circle',
            symbolSize: 5,
            showSymbol: false,
            lineStyle: {
                normal: {
                    color: color[i][0],
                    width: 2
                }
            },
            areaStyle: {
                normal: {
                    color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [{
                        offset: 0,
                        color: color[i][1]
                    }, {
                        offset: 0.8,
                        color: color[i][2]
                    }], false),
                    shadowColor: 'rgba(0, 0, 0, 0.1)',
                }
            },
            itemStyle: {
                normal: {
                    color: color[i][0],
                    borderColor: 'rgba(221, 220, 107, .1)',
                    borderWidth: 12
                }
            },
            data: networkList[list[j].networkName].send
        });
        i++;
        series.push({
            name: list[j].networkName+'↓',
            type: 'line',
            smooth: true,
            symbol: 'circle',
            symbolSize: 5,
            showSymbol: false,
            lineStyle: {
                normal: {
                    color: color[i][0],
                    width: 2
                }
            },
            areaStyle: {
                normal: {
                    color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [{
                        offset: 0,
                        color: color[i][1]
                    }, {
                        offset: 0.8,
                        color: color[i][2]
                    }], false),
                    shadowColor: 'rgba(0, 0, 0, 0.1)',
                }
            },
            itemStyle: {
                normal: {
                    color: color[i][0],
                    borderColor: 'rgba(221, 220, 107, .1)',
                    borderWidth: 12
                }
            },
            data: networkList[list[j].networkName].accept
        });
        i++;
        data.push(list[j].networkName+"↑");
        data.push(list[j].networkName+"↓");
    }
    networkList.timeData.push(time);


    let echartsInstance = echarts.getInstanceByDom(document.querySelector("#network"));
    echartsInstance.setOption({
        legend: {
            data: data
        },
        xAxis: {
            data: networkList.timeData
        },
        series: series
    });
    echartsInstance.hideLoading(); // 去除loading
}